package dian.qing.li.demo.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: pactera
 * @description: 线程池配置
 * @author: EC_liqingdian
 **/
@Configuration
public class ThreadPoolConfig {
    private final int corePoolSize = 10;// 核心线程数（默认线程数）
    private final int maxPoolSize = 200; // 最大线程数
    private final int keepAliveTime = 100;// 允许线程空闲时间（单位：默认为秒）
    private final int queueCapacity = 200;// 缓冲队列数
    private final String threadNamePrefix = "Async-Service-";

    @Bean
    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列最大长度
        executor.setQueueCapacity(queueCapacity);
        //线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(keepAliveTime);
        //线程名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // 线程池对拒绝任务的处理策略：这里采用了CallerRunsPolicy策略，当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
